<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 秒杀前置，微博转发列表
 * @version $Id
 * @author Leo(沈仁贵)
 */
class CLI_Miaosha_Transmit extends CLI
{

    public function main()
    {
        try
        {
	        $start_time = microtime(TRUE);
	        $list = DB::select('sk_id', 'limit_params', 'sk_start_time')
	            ->from('seckill_goods')
	            ->where('status', '=', 0)
	            ->where('sk_start_time', '>', time())
	            ->where('limit_type', '=', 'weibo')
	            ->fetch_all();

	        $weibo_list = Kohana::config('weibo.list');
	        foreach($list as $v)
	        {
	            if($v['sk_start_time'] <= time())
	            {
	                continue;
	            }
	            if( ! empty($v['limit_params']))
	            {
	                $o = unserialize($v['limit_params']);
	                foreach($o as $k => $v)
	                {
	                    if(in_array($k, $weibo_list) AND ! empty($o[$k]))
	                    {
	                        $class = 'Miaosha_Weibo_'.ucfirst($k);
	                        $t = new $class();
	                        $t->set_id($o[$k])->run();
	                    }
	                }
	            }
	        }
	        $end_time = microtime(TRUE);
	        CLI::output('\n拉取秒杀活动微博转发数据，执行用时 '.round($end_time - $start_time, 3).'秒');
        }
        catch(Exception $e)
        {
            DB::delete('cli_running')
                ->where('class', '=', 'CLI_Miaosha_Transmit')
                ->execute();
            CLI::output("\n" . $e->getMessage());
        }
    }
    /**
     * 构造方法
     *
     * @param  CLI_Args  $args
     * @return void
     */
    public function __construct(CLI_Args $args = NULL)
    {
        $this->args = $args;
        if(DB::select('addtime')
            ->from('cli_running')
            ->where('class', '=', get_class($this))
            ->fetch_one())
        {
            CLI::output("\n 此分析器正在运行中");
            die();
        }
        else
        {
            $this->_runed = true;
            DB::insert('cli_running', array('class', 'addtime'))
                ->values(array(get_class($this), time()))
                ->execute();
        }
    }

    /**
     * 删除运行状态
     */
    public function  __destruct()
    {
        if($this->_runed)
        {
            DB::delete('cli_running')->where('class', '=', get_class($this))->execute();
        }
    }
}